import 'dart:math';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:sm_crypto/sm_crypto.dart';

class Sm4Utils {

  static const String keyStr = "smYytongAxun2023";

  static String sm4Encode(String text,{String keyStr = Sm4Utils.keyStr,bool replaceZero = true}){
    String key = SM4.createHexKey(key: keyStr);
    String ebcEncryptData = SM4.encrypt(data: text, key: key);
    return (replaceZero?ebcEncryptData.removeZero():ebcEncryptData).toLowerCase();
  }

  static String sm4Decode(String text,{String keyStr = Sm4Utils.keyStr}){
    String key = SM4.createHexKey(key: keyStr);
    String ebcEncryptData = SM4.decrypt(data: text, key: key);
    return ebcEncryptData;
  }
}

extension Sm4CodeExt on String{

  String get sm4 => this.isNullOrEmpty()?"": Sm4Utils.sm4Encode(this);

  String get defaultSm4 => this.isNullOrEmpty()?"": Sm4Utils.sm4Encode(this,replaceZero: false);

  String get sm4Decode =>Sm4Utils.sm4Decode(this);

  String removeZero(){
    String result = this;
    while (result.length >= 2 && result.endsWith('00')) {
      result = result.substring(0, result.length - 2);
    }
    return result;
  }
}
